<template>
  <div class="material-edit">
    <!-- 物料基本信息头部 -->
    <div class="material-header">
      <div class="header-info">
        <div class="info-row">
          <div class="info-item">
            <span class="label">物料名称：</span>
            <span class="value clickable" @click="showEditDialog">
              {{ materialInfo.materialName || '卷帘门' }}
              <el-icon class="edit-icon"><Edit /></el-icon>
            </span>
          </div>
          <div class="info-item">
            <span class="label">描述：</span>
            <span class="value">{{ materialInfo.remark || '-' }}</span>
          </div>
        </div>
      </div>
      <div class="header-actions">
        <el-button @click="goBack">取消</el-button>
        <el-button v-if="currentStepIndex > 0" @click="goPrevious">上一步</el-button>
        <el-button v-if="currentStepIndex < steps.length - 1" type="primary" @click="goNext"
          >下一步</el-button
        >
        <el-button v-if="currentStepIndex === steps.length - 1" type="primary" @click="goConfirm"
          >确定</el-button
        >
      </div>
    </div>

    <!-- 左侧导航 -->
    <div class="edit-container">
      <div class="sidebar">
        <div class="nav-item" :class="{ active: currentStep === 'upload' }">文件上传</div>
        <div class="nav-item" :class="{ active: currentStep === 'fields' }">字段配置</div>
        <div class="nav-item" :class="{ active: currentStep === 'label' }">标签格式配置</div>
        <div class="nav-item" :class="{ active: currentStep === 'process' }">加工工序配置</div>
        <div class="nav-item" :class="{ active: currentStep === 'production' }">
          生产加工单固定字段配置
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="content">
        <!-- 文件上传步骤 -->
        <div v-if="currentStep === 'upload'" class="step-content">
          <div class="upload-area">
            <el-upload
              ref="uploadRef"
              :file-list="fileList"
              :limit="1"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :http-request="handleUpload"
              :show-file-list="true"
              drag
              class="upload-dragger"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">点击或将文件拖拽到这里上传</div>
              <div class="el-upload__tip">支持扩展名: .xlsx,请使用格式模板</div>
            </el-upload>

            <!-- 上传进度 -->
            <div v-if="uploadProgress > 0" class="upload-progress">
              <el-progress :percentage="uploadProgress" :status="uploadStatus" />
            </div>
          </div>
        </div>

        <!-- 字段配置步骤 -->
        <div v-if="currentStep === 'fields'" class="step-content">
          <div class="step-header">
            <el-button type="primary" @click="addField">添加字段</el-button>
            <el-button @click="previewFields">预览</el-button>
          </div>

          <!-- 表头 -->
          <div class="table-header table-header-fields">
            <div class="header-drag"></div>
            <div class="field-flex-1-7">字段分类</div>
            <div class="field-flex-1-7">字段名称</div>
            <div class="field-flex-1-7">字段英文名称</div>
            <div class="field-flex-1-7">字段类型</div>
            <div class="field-flex-1-7">计算公式</div>
            <div class="field-flex-1-7">是否必填</div>
            <div class="field-actions-header">操作</div>
          </div>

          <draggable v-model="fieldList" :animation="200" ghost-class="ghost" item-key="id">
            <template #item="{ element, index }">
              <div class="field-item" :key="element.id">
                <div class="drag-handle">
                  <el-icon><Rank /></el-icon>
                </div>
                <div class="field-content">
                  <div class="field-flex-1-7">
                    <el-tooltip
                      :content="element.fieldCategory || '-'"
                      placement="top"
                      :disabled="!element.fieldCategory || element.fieldCategory.length <= 20"
                    >
                      <div class="cell-text" :title="element.fieldCategory || '-'">
                        {{ element.fieldCategory || '-' }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="field-flex-1-7">
                    <el-tooltip
                      :content="element.fieldName || '-'"
                      placement="top"
                      :disabled="!element.fieldName || element.fieldName.length <= 20"
                    >
                      <div class="cell-text" :title="element.fieldName || '-'">
                        {{ element.fieldName || '-' }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="field-flex-1-7">
                    <el-tooltip
                      :content="element.fieldEnglishName || '-'"
                      placement="top"
                      :disabled="!element.fieldEnglishName || element.fieldEnglishName.length <= 20"
                    >
                      <div class="cell-text" :title="element.fieldEnglishName || '-'">
                        {{ element.fieldEnglishName || '-' }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="field-flex-1-7">
                    <el-tooltip
                      :content="getFieldTypeName(element.fieldType)"
                      placement="top"
                      :disabled="
                        !getFieldTypeName(element.fieldType) ||
                        getFieldTypeName(element.fieldType).length <= 20
                      "
                    >
                      <div class="cell-text" :title="getFieldTypeName(element.fieldType)">
                        {{ getFieldTypeName(element.fieldType) }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="field-flex-1-7">
                    <el-tooltip
                      :content="element.formula || '/'"
                      placement="top"
                      :disabled="!element.formula || element.formula === '/'"
                    >
                      <div class="cell-text" :title="element.formula || '/'">
                        {{ element.formula || '/' }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="field-flex-1-7">
                    <div class="cell-text">{{ element.isRequired ? '是' : '否' }}</div>
                  </div>
                  <div class="field-actions">
                    <el-link :underline="false" type="primary" @click="editField(element)"
                      >编辑</el-link
                    >
                    <el-link :underline="false" type="danger" @click="removeField(element)"
                      >移除</el-link
                    >
                  </div>
                </div>
              </div>
            </template>
          </draggable>
        </div>

        <!-- 标签格式配置步骤 -->
        <div v-if="currentStep === 'label'" class="step-content">
          <div class="label-config-container">
            <!-- 左侧固定显示可拖拽元素 -->
            <div class="label-source-panel">
              <div class="source-title">拖拽元素</div>
              <div class="source-items">
                <div class="source-item" draggable="true" @dragstart="handleDragStart($event, 1)">
                  <el-icon><Document /></el-icon>
                  <span>物料字段</span>
                </div>
                <div class="source-item" draggable="true" @dragstart="handleDragStart($event, 2)">
                  <el-icon><Edit /></el-icon>
                  <span>文本输入</span>
                </div>
                <div class="source-item" draggable="true" @dragstart="handleDragStart($event, 3)">
                  <el-icon><Grid /></el-icon>
                  <span>条形码</span>
                </div>
                <div class="source-item" draggable="true" @dragstart="handleDragStart($event, 4)">
                  <el-icon><Grid /></el-icon>
                  <span>二维码</span>
                </div>
              </div>
            </div>

            <!-- 右侧配置区域 -->
            <div class="label-config-panel">
              <!-- 头部表单 -->
              <div class="label-header-form">
                <el-form :model="labelConfig" label-width="120px" inline>
                  <el-form-item label="标签比例" prop="labelProp" required>
                    <el-select
                      v-model="labelConfig.labelProp"
                      placeholder="请选择"
                      style="width: 200px"
                    >
                      <el-option label="1:3" :value="1" />
                      <el-option label="2:3" :value="2" />
                    </el-select>
                  </el-form-item>
                  <el-form-item prop="associatedLabels" required>
                    <template #label>
                      <span>可关联标签</span>
                      <el-tooltip
                        content="将通过主编码关联多个不同的标签，各个标签间存在关联。可填写范围：1～5"
                        placement="top"
                      >
                        <el-icon class="info-icon"><QuestionFilled /></el-icon>
                      </el-tooltip>
                    </template>
                    <el-input-number
                      v-model="labelConfig.associatedLabels"
                      :min="1"
                      :max="5"
                      style="width: 200px"
                    />
                  </el-form-item>
                </el-form>
              </div>

              <!-- 主区域：自定义标签行数据 -->
              <div
                class="label-items-wrapper"
                @drop="handleDrop"
                @dragover.prevent
                @dragenter.prevent
              >
                <div class="label-items-container">
                  <div
                    v-for="(item, index) in sortedLabelItems"
                    :key="item.id"
                    class="label-item-card"
                  >
                    <!-- 物料字段类型 type=1 -->
                    <template v-if="item.type === 1">
                      <div class="item-left">
                        <el-select
                          v-model="item.fieldId"
                          placeholder="请选择"
                          style="width: 100%"
                          @change="validateLabelItems"
                        >
                          <el-option
                            v-for="field in fieldList"
                            :key="field.id"
                            :label="field.fieldName"
                            :value="field.id"
                          />
                        </el-select>
                      </div>
                      <div class="item-right">
                        <span class="auto-fetch-text">自动获取数据</span>
                      </div>
                    </template>

                    <!-- 文本输入类型 type=2 -->
                    <template v-else-if="item.type === 2">
                      <div class="item-left">
                        <el-input
                          v-model="item.leftText"
                          placeholder="请输入"
                          @input="validateLabelItems"
                        />
                      </div>
                      <div class="item-right">
                        <el-input
                          v-model="item.rightText"
                          placeholder="请输入"
                          @input="validateLabelItems"
                        />
                      </div>
                    </template>

                    <!-- 条形码类型 type=3 -->
                    <template v-else-if="item.type === 3">
                      <div class="item-left">
                        <span class="item-label">条形码</span>
                      </div>
                      <div class="item-right">
                        <div class="barcode-preview">
                          <img
                            src="@/assets/images/barcode.svg"
                            alt="条形码"
                            class="barcode-image"
                          />
                        </div>
                      </div>
                    </template>

                    <!-- 二维码类型 type=4 -->
                    <template v-else-if="item.type === 4">
                      <div class="item-left">
                        <span class="item-label">二维码</span>
                      </div>
                      <div class="item-right">
                        <div class="qrcode-preview">
                          <img src="@/assets/images/qrcode.png" alt="二维码" class="qrcode-image" />
                        </div>
                      </div>
                    </template>

                    <!-- 删除按钮 -->
                    <div class="item-delete">
                      <el-icon class="delete-icon" @click="removeLabelItem(index)"
                        ><Delete
                      /></el-icon>
                    </div>
                  </div>

                  <!-- 空状态提示 -->
                  <div v-if="sortedLabelItems.length === 0" class="empty-state">
                    <div class="empty-text">拖拽左侧元素到此处添加标签配置</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 加工工序配置步骤 -->
        <div v-if="currentStep === 'process'" class="step-content">
          <div class="alert-info">
            <el-alert
              title="此处填写内容影响生产管理模块-生产加工单，业务人员对生产加工单状态的设置"
              type="warning"
              :closable="false"
            />
          </div>
          <div class="step-header">
            <el-button type="primary" @click="addProcessStep">添加步骤</el-button>
          </div>

          <!-- 表头 -->
          <div class="table-header table-header-process">
            <div class="header-drag"></div>
            <div class="process-flex-1-3">序号</div>
            <div class="process-flex-1-3">步骤名称</div>
            <div class="process-actions-header">操作</div>
          </div>

          <draggable
            v-model="processList"
            :animation="200"
            ghost-class="ghost"
            @end="onProcessDragEnd"
            item-key="id"
          >
            <template #item="{ element, index }">
              <div class="process-item" :key="element.id || element.order">
                <div class="drag-handle">
                  <el-icon><Rank /></el-icon>
                </div>
                <div class="process-content">
                  <div class="process-flex-1-3">
                    <div class="cell-text">{{ index + 1 }}</div>
                  </div>
                  <div class="process-flex-1-3">
                    <el-tooltip
                      :content="element.name || '-'"
                      placement="top"
                      :disabled="!element.name || element.name.length <= 20"
                    >
                      <div class="cell-text" :title="element.name || '-'">
                        {{ element.name || '-' }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="process-actions">
                    <el-link :underline="false" type="primary" @click="editProcessStep(element)"
                      >编辑</el-link
                    >
                    <el-link :underline="false" type="danger" @click="deleteProcessStep(element)"
                      >删除</el-link
                    >
                  </div>
                </div>
              </div>
            </template>
          </draggable>
        </div>

        <!-- 生产加工单固定字段配置步骤 -->
        <div v-if="currentStep === 'production'" class="step-content">
          <div class="alert-info">
            <el-alert
              title="此处填写内容影响生产管理模块-生产加工单打印时的信息展示"
              type="warning"
              :closable="false"
            />
          </div>
          <div class="step-header">
            <el-button type="primary" @click="addProductionField">添加字段</el-button>
            <el-button @click="previewProductionFields">预览</el-button>
          </div>

          <!-- 表头 -->
          <div class="table-header table-header-production">
            <div class="header-drag"></div>
            <div class="production-flex-1-4">字段名称</div>
            <div class="production-flex-1-4">展示方式</div>
            <div class="production-flex-1-4">展示逻辑</div>
            <div class="production-actions-header">操作</div>
          </div>

          <draggable
            v-model="productionFieldList"
            :animation="200"
            ghost-class="ghost"
            item-key="id"
          >
            <template #item="{ element, index }">
              <div class="production-item" :key="element.id">
                <div class="drag-handle">
                  <el-icon><Rank /></el-icon>
                </div>
                <div class="production-content">
                  <div class="production-flex-1-4">
                    <el-tooltip
                      :content="element.fieldName || '-'"
                      placement="top"
                      :disabled="!element.fieldName || element.fieldName.length <= 20"
                    >
                      <div class="cell-text" :title="element.fieldName || '-'">
                        {{ element.fieldName || '-' }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="production-flex-1-4">
                    <el-tooltip
                      :content="getShowTypeName(element.showType)"
                      placement="top"
                      :disabled="
                        !element.showType || getShowTypeName(element.showType).length <= 20
                      "
                    >
                      <div class="cell-text" :title="getShowTypeName(element.showType)">
                        {{ getShowTypeName(element.showType) }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="production-flex-1-4">
                    <el-tooltip
                      :content="getLogicTypeName(element.logicType)"
                      placement="top"
                      :disabled="
                        !element.logicType || getLogicTypeName(element.logicType).length <= 20
                      "
                    >
                      <div class="cell-text" :title="getLogicTypeName(element.logicType)">
                        {{ getLogicTypeName(element.logicType) }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="production-actions">
                    <el-link :underline="false" type="primary" @click="editProductionField(element)"
                      >编辑</el-link
                    >
                    <el-link
                      :underline="false"
                      type="danger"
                      @click="deleteProductionField(element)"
                      >删除</el-link
                    >
                  </div>
                </div>
              </div>
            </template>
          </draggable>
        </div>
      </div>
    </div>

    <!-- 编辑物料信息弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑" width="520px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="84px">
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="editForm.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="所属分类" prop="classification">
          <el-select v-model="editForm.classification" placeholder="请选择分类" style="width: 100%">
            <el-option label="防火门" value="fire_door" />
            <el-option label="卷帘门" value="roller_door" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="支持1~128字符"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加步骤弹窗 -->
    <el-dialog v-model="addStepDialogVisible" title="添加步骤" width="520px">
      <el-form :model="stepForm" :rules="stepRules" ref="stepFormRef" label-width="84px">
        <el-form-item label="步骤名称" prop="name">
          <el-input v-model="stepForm.name" placeholder="请输入步骤名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addStepDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStep">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑字段弹窗 -->
    <FieldDialog
      v-model:visible="fieldDialogVisible"
      :field-list="fieldList"
      :field-data="editingFieldData"
      :material-id="route.params.id"
      @success="handleFieldSuccess"
    />

    <!-- 生产加工单固定字段配置弹窗 -->
    <ProductionFieldDialog
      v-model:visible="productionFieldDialogVisible"
      :field-list="fieldList"
      :production-field-list="productionFieldList"
      :production-field-data="editingProductionFieldData"
      @success="handleProductionFieldSuccess"
    />

    <!-- 字段预览弹窗 -->
    <FieldPreviewDialog v-model:visible="fieldPreviewDialogVisible" :field-list="fieldList" />
  </div>
</template>

<script setup>
import {
  editorBasicMaterial,
  editorMaterial,
  getById,
  uploadTemplate
} from '@/api/system/materials'
import {
  Delete,
  Document,
  Edit,
  Grid,
  QuestionFilled,
  Rank,
  UploadFilled
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import draggable from 'vuedraggable'
import FieldDialog from './components/FieldDialog.vue'
import FieldPreviewDialog from './components/FieldPreviewDialog.vue'
import ProductionFieldDialog from './components/ProductionFieldDialog.vue'

const route = useRoute()
const router = useRouter()

// 当前步骤
const currentStep = ref('upload')
const steps = ['upload', 'fields', 'label', 'process', 'production']
const currentStepIndex = ref(0)

// 物料信息
const materialInfo = reactive({
  materialName: '-',
  remark: '-',
  materialCode: '-',
  version: '-',
  status: '1',
  classification: null
})

// 文件上传
const fileList = ref([])
const uploadRef = ref()
const uploadProgress = ref(0)
const uploadStatus = ref('')
const hasUploadedFile = ref(false) // 标记是否已上传过文件
const pendingFieldData = ref(null) // 临时存储上传后的字段数据，等待用户确认覆盖

// 字段配置
const fieldList = ref([])

// 标签配置
const labelConfig = reactive({
  labelProp: 1,
  associatedLabels: 1,
  items: [] // 自定义标签行数据
})

// 标签项ID计数器
let labelItemIdCounter = 0

// 当前拖拽的元素类型（1=物料字段, 2=文本输入, 3=条形码, 4=二维码）
const draggingType = ref(null)

// 排序后的标签项列表（按物料字段、文本输入、条形码、二维码顺序）
const sortedLabelItems = computed(() => {
  return [...labelConfig.items].sort((a, b) => {
    return (a.type || 999) - (b.type || 999)
  })
})

// 加工工序配置
const processList = ref([])

// 生产加工单固定字段配置
const productionFieldList = ref([])

// 编辑弹窗
const editDialogVisible = ref(false)
const editFormRef = ref()
const editForm = reactive({
  materialName: '',
  classification: '',
  description: ''
})
const editRules = {
  materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  classification: [{ required: true, message: '请选择分类', trigger: 'change' }]
}

// 添加步骤弹窗
const addStepDialogVisible = ref(false)
const stepFormRef = ref()
const stepForm = reactive({
  name: ''
})
const stepRules = {
  name: [{ required: true, message: '请输入步骤名称', trigger: 'blur' }]
}

// 添加/编辑字段弹窗
const fieldDialogVisible = ref(false)
const editingFieldData = ref(null)

// 字段预览弹窗
const fieldPreviewDialogVisible = ref(false)

// 生产加工单固定字段配置弹窗
const productionFieldDialogVisible = ref(false)
const editingProductionFieldData = ref(null)

function goBack() {
  router.back()
}

function goPrevious() {
  if (currentStepIndex.value > 0) {
    currentStepIndex.value--
    currentStep.value = steps[currentStepIndex.value]
  }
}

async function goNext() {
  // 如果当前在标签格式配置步骤，需要校验标签配置是否完整
  if (currentStep.value === 'label') {
    // 必须配置至少一项才能进入下一步
    if (!labelConfig.items || labelConfig.items.length === 0) {
      ElMessage.warning('请至少配置一项标签格式')
      return
    }
    const validation = validateLabelConfig()
    if (!validation.valid) {
      ElMessage.warning(validation.message)
      return
    }
  }

  // 如果当前在文件上传步骤，需要校验是否有字段配置数据
  if (currentStep.value === 'upload') {
    // 如果字段列表为空且没有待覆盖数据，需要先上传文件
    if ((!fieldList.value || fieldList.value.length === 0) && !pendingFieldData.value) {
      ElMessage.warning('请先上传文件获取字段配置数据后，才能进行下一步操作')
      return
    }

    // 如果有待覆盖的字段数据，并且当前已有字段配置，提示用户确认是否覆盖
    if (pendingFieldData.value && fieldList.value && fieldList.value.length > 0) {
      try {
        await ElMessageBox.confirm('检测到新上传的字段配置数据，是否覆盖当前字段配置？', '提示', {
          type: 'warning',
          confirmButtonText: '覆盖',
          cancelButtonText: '保留当前配置'
        })
        // 用户确认覆盖
        // 保存旧字段列表的引用（用于同步删除时匹配）
        const oldFieldList = [...fieldList.value]
        // 获取旧字段ID列表
        const oldFieldIds = fieldList.value.map((field) => field.id)
        // 获取新字段ID列表
        const newFieldIds = pendingFieldData.value.map((field) => field.id)
        // 找出被删除的字段ID
        const deletedFieldIds = oldFieldIds.filter((id) => !newFieldIds.includes(id))

        // 更新字段列表
        fieldList.value = pendingFieldData.value

        // 同步删除相关字段配置（传入旧字段列表用于匹配）
        if (deletedFieldIds.length > 0) {
          syncDeleteRelatedFields(deletedFieldIds, oldFieldList)
        }

        pendingFieldData.value = null
      } catch {
        // 用户选择保留当前配置，重置文件上传初始状态
        pendingFieldData.value = null
        fileList.value = []
        uploadProgress.value = 0
        uploadStatus.value = ''
      }
    } else if (pendingFieldData.value && (!fieldList.value || fieldList.value.length === 0)) {
      // 如果有待覆盖数据但当前没有字段配置，直接使用上传的数据
      // 这种情况下，需要清空所有相关配置，因为字段列表被完全替换
      fieldList.value = pendingFieldData.value
      // 清空标签格式配置中的物料字段选择(type=1)
      labelConfig.items = labelConfig.items.filter((item) => item.type !== 1)
      // 清空生产加工单固定字段配置
      productionFieldList.value = []
      pendingFieldData.value = null
    }
  }

  if (currentStepIndex.value < steps.length - 1) {
    currentStepIndex.value++
    currentStep.value = steps[currentStepIndex.value]
  }
}

// 解析计算公式，将字段英文名称转换为字段ID
function parseFormula(formulaStr, fieldList) {
  if (!formulaStr) return ''

  // 公式格式可能是：field1*field2 或 65277,+,65278
  // 先尝试解析为字段ID格式
  if (/^\d+[,+\-*/]\d+$/.test(formulaStr.replace(/\s/g, ''))) {
    // 已经是ID格式
    return formulaStr
  }

  // 解析为字段英文名称格式，需要转换为ID
  const operators = ['+', '-', '*', '/']
  let operator = ''
  let leftField = ''
  let rightField = ''

  for (const op of operators) {
    if (formulaStr.includes(op)) {
      operator = op
      const parts = formulaStr.split(op)
      leftField = parts[0]?.trim()
      rightField = parts[1]?.trim()
      break
    }
  }

  if (!operator || !leftField || !rightField) {
    return formulaStr
  }

  // 查找字段ID
  const leftFieldObj = fieldList.find((f) => f.fieldEnglishName === leftField)
  const rightFieldObj = fieldList.find((f) => f.fieldEnglishName === rightField)

  if (leftFieldObj && rightFieldObj) {
    return `${leftFieldObj.id},${operator},${rightFieldObj.id}`
  }

  return formulaStr
}

async function goConfirm() {
  try {
    const materialId = route.params.id
    if (!materialId) {
      ElMessage.error('物料ID不存在')
      return
    }

    // 转换标签配置
    const labelConfiguration = sortedLabelItems.value.map((item, index) => {
      const config = {
        location: index + 1, // 序号从1开始
        type: item.type || 1, // 1=物料字段, 2=文本输入, 3=条形码, 4=二维码
        id: '',
        value: ''
      }

      if (item.type === 1) {
        // type=1: 物料字段类型
        config.id = item.fieldId || ''
      } else if (item.type === 2) {
        // type=2: 文本输入类型，value为输入的内容
        const leftValue = item.leftText || ''
        const rightValue = item.rightText || ''
        config.value =
          leftValue && rightValue ? `${leftValue},${rightValue}` : leftValue || rightValue || ''
      }
      // type=3(条形码)和type=4(二维码)的id和value都为空

      return config
    })

    // 转换加工工序配置
    const processConfiguration = processList.value.map((item, index) => ({
      serialNumber: item.order || index + 1,
      name: item.name || '',
      id: item.id || ''
    }))

    // 转换字段配置
    const fieldConfiguration = fieldList.value.map((field, index) => {
      const config = {
        serialNumber: field.serialNumber || index + 1,
        id: field.id ? String(field.id) : '', // 新增时为空字符串，修改时必传
        fieldCategory: field.fieldCategory || '',
        fieldName: field.fieldName || '',
        fieldEnglishName: field.fieldEnglishName || '',
        fieldType: field.fieldType || 4, // 直接使用字段类型值
        isFormula: field.isFormula ? 1 : 0,
        formula: '',
        isRequired:
          field.isRequired !== undefined && field.isRequired !== null
            ? field.isRequired
              ? 1
              : 0
            : 1,
        enumerationValue: '',
        value: field.value || {}
      }

      // 转换计算公式
      if (field.isFormula && field.formula) {
        config.formula = parseFormula(field.formula, fieldList.value)
      }

      // 转换枚举值
      if (field.fieldType === 5 && field.enumOptions && field.enumOptions.length > 0) {
        // 确保枚举值是数组格式
        const enumArray = Array.isArray(field.enumOptions)
          ? field.enumOptions
          : field.enumOptions.map((opt) => (typeof opt === 'string' ? opt : opt.value || opt))
        config.enumerationValue = JSON.stringify(enumArray)
      }

      return config
    })

    // 转换生产加工单固定字段配置
    const processingOrderConfiguration = productionFieldList.value.map((item, index) => {
      const config = {
        serialNumber: index + 1,
        id: item.id || '',
        showType: item.showType || 1,
        logicType: null
      }

      // 如果展示方式是计算展示，需要设置展示逻辑
      if (item.showType === 3 && item.logicType) {
        config.logicType = item.logicType
      }

      // 如果id为空，尝试通过fieldName查找
      if (!config.id && item.fieldName) {
        const field = fieldList.value.find((f) => f.fieldName === item.fieldName)
        if (field) {
          config.id = field.id
        }
      }

      return config
    })

    // 构建请求参数
    const params = {
      id: Number(materialId),
      labelProp: labelConfig.labelProp,
      associatedLabels: labelConfig.associatedLabels || 1,
      labelConfigurationEntities: labelConfiguration,
      processConfigurationEntities: processConfiguration,
      fieldConfigurationEntities: fieldConfiguration,
      processingOrderConfigurationEntities: processingOrderConfiguration
    }

    // 调用保存接口
    await editorMaterial(params)
    ElMessage.success('保存成功')

    // 保存成功后跳转到物料管理列表
    router.push({ path: '/system/materials' })
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请重试')
  }
}

// 分类映射：字符串值 -> 数字ID
const classificationMap = {
  fire_door: 1,
  roller_door: 2,
  1: 'fire_door',
  2: 'roller_door'
}

function showEditDialog() {
  editForm.materialName = materialInfo.materialName
  // 如果物料信息中有分类ID，转换为字符串值；否则使用默认值
  const classificationId = materialInfo.classification
  editForm.classification = classificationId
    ? classificationMap[classificationId] || 'fire_door'
    : 'fire_door'
  editForm.description = materialInfo.remark
  editDialogVisible.value = true
}

async function saveEdit() {
  await editFormRef.value?.validate()

  try {
    const materialId = route.params.id
    if (!materialId) {
      ElMessage.error('物料ID不存在')
      return
    }

    // 将字符串分类值转换为数字ID
    const classificationId = classificationMap[editForm.classification]
    if (!classificationId) {
      ElMessage.error('分类选择无效')
      return
    }

    // 构建请求参数
    const params = {
      id: Number(materialId),
      materialName: editForm.materialName,
      classification: classificationId,
      remark: editForm.description || ''
    }

    // 调用编辑物料基础信息接口
    await editorBasicMaterial(params)

    // 更新本地状态
    materialInfo.materialName = editForm.materialName
    materialInfo.remark = editForm.description
    materialInfo.classification = classificationId

    editDialogVisible.value = false
    ElMessage.success('物料基础信息保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请重试')
  }
}

// 文件上传相关
function handleExceed() {
  ElMessage.warning('只能上传一个文件')
}

function beforeUpload(file) {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件')
    return false
  }
  return true
}

function handleFileChange(file, fileList) {
  if (fileList.length > 1) {
    fileList.splice(0, 1)
  }
}

function handleFileRemove() {
  fileList.value = []
  uploadProgress.value = 0
  uploadStatus.value = ''
  // 移除文件时，清除待覆盖的字段数据
  pendingFieldData.value = null
  // 如果字段列表为空，重置标记
  if (!fieldList.value || fieldList.value.length === 0) {
    hasUploadedFile.value = false
  }
}

async function handleUpload(options) {
  const { file } = options
  uploadProgress.value = 0
  uploadStatus.value = 'uploading'

  try {
    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', file)
    formData.append('id', route.params.id) // 传递物料ID

    // 调用上传模板接口
    const res = await uploadTemplate(formData)
    uploadProgress.value = 100
    uploadStatus.value = 'success'

    // 如果上传成功，处理返回的字段数据
    if (res.data && res.data.length > 0) {
      // 标记已上传过文件
      hasUploadedFile.value = true
      // 将返回的字段数据保存到临时变量，等待用户确认后再覆盖
      pendingFieldData.value = res.data
      ElMessage.success(`文件上传成功，成功解析 ${res.data.length} 个字段`)
    }
  } catch (error) {
    uploadProgress.value = 0
    uploadStatus.value = 'exception'
    ElMessage.error('文件上传失败')
  }
}

// 获取字段类型名称（直接使用接口类型值）
function getFieldTypeName(fieldType) {
  return (
    {
      1: '两位小数',
      2: '整数',
      3: '日期',
      4: '文本',
      5: '枚举'
    }[fieldType] || '未知'
  )
}

// 获取展示方式名称
function getShowTypeName(showType) {
  return (
    {
      1: '表格展示',
      2: '分组展示',
      3: '计算展示'
    }[showType] || '-'
  )
}

// 获取计算逻辑名称
function getLogicTypeName(logicType) {
  return (
    {
      1: '统计',
      2: '平均'
    }[logicType] || '-'
  )
}

// 字段配置相关
function addField() {
  editingFieldData.value = null
  fieldDialogVisible.value = true
}

function previewFields() {
  if (fieldList.value.length === 0) {
    ElMessage.warning('请先添加字段')
    return
  }
  fieldPreviewDialogVisible.value = true
}

function editField(row) {
  editingFieldData.value = { ...row }
  fieldDialogVisible.value = true
}

// 处理字段保存成功
function handleFieldSuccess(fieldData, isEdit) {
  if (isEdit) {
    const index = fieldList.value.findIndex((f) => f.id === fieldData.id)
    if (index !== -1) {
      fieldList.value[index] = { ...fieldList.value[index], ...fieldData }
      ElMessage.success('字段编辑成功')
    }
  } else {
    fieldList.value.push(fieldData)
    ElMessage.success('字段添加成功')
  }
}

// 同步删除相关字段配置
function syncDeleteRelatedFields(deletedFieldIds, oldFieldList = null) {
  if (!deletedFieldIds || deletedFieldIds.length === 0) return

  // 使用旧字段列表或当前字段列表进行匹配
  const fieldListForMatch = oldFieldList || fieldList.value

  // 删除标签格式配置中已选择的物料字段
  labelConfig.items = labelConfig.items.filter((item) => {
    // 如果是物料字段类型(type=1)，检查fieldId是否在删除列表中
    if (item.type === 1 && item.fieldId) {
      return !deletedFieldIds.includes(item.fieldId)
    }
    // 其他类型(type=2文本输入, type=3条形码, type=4二维码)保留
    return true
  })

  // 删除生产加工单固定字段配置列表中的字段
  productionFieldList.value = productionFieldList.value.filter((item) => {
    // 通过id直接匹配
    if (item.id && deletedFieldIds.includes(item.id)) {
      return false
    }
    // 如果通过fieldName匹配，需要在旧字段列表中查找对应的id
    if (item.fieldName && fieldListForMatch) {
      const oldField = fieldListForMatch.find((f) => f.fieldName === item.fieldName)
      if (oldField && deletedFieldIds.includes(oldField.id)) {
        return false
      }
    }
    return true
  })
}

function removeField(row) {
  const index = fieldList.value.findIndex((item) => item.id === row.id)
  if (index > -1) {
    fieldList.value.splice(index, 1)
    // 同步删除相关字段配置
    syncDeleteRelatedFields([row.id])
  }
}

// 标签配置相关
// 拖拽开始
function handleDragStart(event, type) {
  draggingType.value = type
  event.dataTransfer.effectAllowed = 'copy'
}

// 拖拽放置
function handleDrop(event) {
  event.preventDefault()
  if (!draggingType.value) return

  // 检查条形码和二维码是否已存在
  if (draggingType.value === 3) {
    const exists = labelConfig.items.some((item) => item.type === 3)
    if (exists) {
      ElMessage.warning('条形码只能添加一次')
      draggingType.value = null
      return
    }
  } else if (draggingType.value === 4) {
    const exists = labelConfig.items.some((item) => item.type === 4)
    if (exists) {
      ElMessage.warning('二维码只能添加一次')
      draggingType.value = null
      return
    }
  }

  const newItem = {
    id: ++labelItemIdCounter,
    type: draggingType.value
  }

  // 根据类型初始化不同的数据结构
  if (draggingType.value === 1) {
    // type=1: 物料字段
    newItem.fieldId = ''
  } else if (draggingType.value === 2) {
    // type=2: 文本输入
    newItem.leftText = ''
    newItem.rightText = ''
  }

  labelConfig.items.push(newItem)
  draggingType.value = null
  validateLabelItems()
}

// 删除标签项
function removeLabelItem(index) {
  // index 是排序后的索引，需要找到原始数组中的索引
  const sortedItems = sortedLabelItems.value
  const itemToRemove = sortedItems[index]
  if (itemToRemove) {
    const originalIndex = labelConfig.items.findIndex((item) => item.id === itemToRemove.id)
    if (originalIndex !== -1) {
      labelConfig.items.splice(originalIndex, 1)
      validateLabelItems()
    }
  }
}

// 验证标签项（检查必填项）
function validateLabelItems() {
  // 验证逻辑在 goNext 中调用
}

// 验证标签配置是否完整
function validateLabelConfig() {
  // 验证头部表单
  if (!labelConfig.labelProp) {
    return { valid: false, message: '请选择标签比例' }
  }
  if (!labelConfig.associatedLabels || labelConfig.associatedLabels < 1) {
    return { valid: false, message: '请设置可关联标签数量' }
  }

  // 验证所有行数据
  for (let i = 0; i < labelConfig.items.length; i++) {
    const item = labelConfig.items[i]
    if (item.type === 1) {
      // type=1: 物料字段
      if (!item.fieldId) {
        return { valid: false, message: `第${i + 1}行：请选择物料字段` }
      }
    } else if (item.type === 2) {
      // type=2: 文本输入
      if (!item.leftText || !item.rightText) {
        return { valid: false, message: `第${i + 1}行：请完整填写文本输入` }
      }
    }
    // type=3(条形码)和type=4(二维码)不需要验证（显示即可）
  }

  return { valid: true }
}

// 加工工序配置相关
function addProcessStep() {
  addStepDialogVisible.value = true
}

function editProcessStep(row) {
  ElMessage.info('编辑步骤功能待实现')
}

function deleteProcessStep(row) {
  if (row.name === '入库') {
    ElMessage.warning('入库步骤不能删除')
    return
  }
  // 使用 id 或同时匹配 order 和 name 来确保唯一性
  const index = processList.value.findIndex((item) => {
    if (row.id && item.id) {
      return item.id === row.id
    }
    // 如果没有 id，使用 order 和 name 同时匹配
    return item.order === row.order && item.name === row.name
  })
  if (index > -1) {
    processList.value.splice(index, 1)
    // 重新排序
    processList.value.forEach((item, index) => {
      item.order = index + 1
    })
  }
}

async function saveStep() {
  await stepFormRef.value?.validate()
  // 检查重名
  const exists = processList.value.some((item) => item.name === stepForm.name)
  if (exists) {
    ElMessage.error('该步骤名称已存在')
    return
  }

  // 添加新步骤（入库前）
  const newOrder = processList.value.length
  // 生成唯一的 id（如果已有 id，则使用最大值+1，否则使用时间戳）
  const maxId =
    processList.value.length > 0 ? Math.max(...processList.value.map((item) => item.id || 0), 0) : 0
  const newId = maxId > 0 ? maxId + 1 : Date.now()
  processList.value.splice(newOrder - 1, 0, {
    id: newId,
    order: newOrder,
    name: stepForm.name
  })

  // 重新排序
  processList.value.forEach((item, index) => {
    item.order = index + 1
  })

  addStepDialogVisible.value = false
  stepForm.name = ''
  ElMessage.success('添加成功')
}

// 生产加工单固定字段配置相关
function addProductionField() {
  if (!fieldList.value || fieldList.value.length === 0) {
    ElMessage.warning('请先配置字段列表')
    return
  }

  // 检查是否所有字段都已被使用
  const usedFieldNames = productionFieldList.value.map((item) => item.fieldName)
  const availableFields = fieldList.value.filter(
    (field) => !usedFieldNames.includes(field.fieldName)
  )

  if (availableFields.length === 0) {
    ElMessage.warning('所有字段都已被使用，一个字段只能添加一次')
    return
  }

  editingProductionFieldData.value = null
  productionFieldDialogVisible.value = true
}

function previewProductionFields() {
  ElMessage.info('预览功能待实现')
}

function editProductionField(row) {
  editingProductionFieldData.value = { ...row }
  productionFieldDialogVisible.value = true
}

function deleteProductionField(row) {
  // 使用 id 或 fieldName 来匹配，确保能正确删除
  const index = productionFieldList.value.findIndex((item) => {
    // 优先使用 id 匹配（更可靠）
    if (row.id && item.id) {
      return item.id === row.id
    }
    // 如果 id 不存在，使用 fieldName 匹配
    if (row.fieldName && item.fieldName) {
      return item.fieldName === row.fieldName
    }
    return false
  })
  if (index > -1) {
    productionFieldList.value.splice(index, 1)
  } else {
    ElMessage.warning('未找到要删除的字段')
  }
}

// 处理生产加工单固定字段保存成功
function handleProductionFieldSuccess(productionFieldData, isEdit) {
  if (isEdit) {
    const index = productionFieldList.value.findIndex((f) => f.id === productionFieldData.id)
    if (index !== -1) {
      productionFieldList.value[index] = {
        ...productionFieldList.value[index],
        ...productionFieldData
      }
      ElMessage.success('字段编辑成功')
    }
  } else {
    productionFieldList.value.push(productionFieldData)
    ElMessage.success('字段添加成功')
  }
}

// 拖拽相关方法
function onProcessDragEnd() {
  // 重新排序工序
  processList.value.forEach((item, index) => {
    item.order = index + 1
  })
}

// 获取物料详情
async function fetchMaterialDetail() {
  const materialId = route.params.id
  if (!materialId) {
    ElMessage.error('物料ID不存在')
    return
  }

  try {
    const res = await getById({ id: materialId })
    if (res.data) {
      // 回显物料基本信息
      materialInfo.materialName = res.data.materialName || ''
      materialInfo.remark = res.data.remark || ''
      materialInfo.materialCode = res.data.materialCode || ''
      materialInfo.version = res.data.version || ''
      materialInfo.status = res.data.status || '1'
      materialInfo.classification = res.data.classification || null

      // 解析字段数据
      fieldList.value = res.data.fieldConfigurationToEntity || []

      // 解析工序数据
      processList.value = (res.data.processConfigurationToEntity || []).map((item, index) => {
        // 确保每个工序都有唯一的 id
        if (!item.id) {
          item.id = Date.now() + index
        }
        return item
      })

      // 解析固定字段数据
      productionFieldList.value = res.data.fixedFieldToEntity || []

      // 解析标签数据
      labelConfig.labelProp = res.data.labelProp || 1
      labelConfig.associatedLabels = res.data.associatedLabels || 1
      const labelData = res.data.labelConfigurationToEntity || []
      // 转换接口返回的数据格式为前端使用的格式
      labelConfig.items = (labelData || []).map((item, index) => {
        const convertedItem = {
          id: ++labelItemIdCounter, // 前端使用的唯一标识ID（标签项本身）
          type: item.type || 1 // 1=物料字段, 2=文本输入, 3=条形码, 4=二维码
        }

        // type=1: 物料字段，需要 fieldId（接口返回的 id 就是字段id）
        if (item.type === 1) {
          convertedItem.fieldId = item.id || ''
        }
        // type=2: 文本输入，需要 leftText 和 rightText
        else if (item.type === 2) {
          // 接口返回的 value 格式是 "leftText,rightText"
          const valueParts = (item.value || '').split(',')
          convertedItem.leftText = valueParts[0] || ''
          convertedItem.rightText = valueParts[1] || ''
        }
        // type=3(条形码)和type=4(二维码)不需要额外字段

        return convertedItem
      })

      // 如果字段配置有数据，默认跳到字段配置步骤
      if (fieldList.value && fieldList.value.length > 0) {
        currentStep.value = 'fields'
        currentStepIndex.value = 1
        // 标记已上传过文件（从接口获取的数据）
        hasUploadedFile.value = true
      }
    }
  } catch (error) {}
}

onMounted(() => {
  // 初始化数据
  fetchMaterialDetail()
})
</script>

<style lang="scss" scoped>
.material-edit {
  background: #fff;
  border-radius: 6px;
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  font-size: 14px;

  .material-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;

    .header-info {
      flex: 1;

      .info-row {
        display: flex;
        margin-bottom: 12px;
        gap: 40px;

        .info-item {
          display: flex;
          align-items: center;
          min-width: 200px;

          .label {
            color: #606266;
            font-weight: 500;
            margin-right: 8px;
          }

          .value {
            color: #303133;

            &.clickable {
              cursor: pointer;
              color: #409eff;
              display: flex;
              align-items: center;
              gap: 4px;

              &:hover {
                text-decoration: underline;
              }
            }
          }
        }
      }
    }

    .header-actions {
      margin-left: 20px;
    }
  }

  .edit-container {
    display: flex;
    flex: 1;
    min-height: 0;

    .sidebar {
      width: 200px;
      background: #f8f9fa;
      border-radius: 6px;
      padding: 8px;
      margin-right: 16px;

      .nav-item {
        padding: 8px 0 8px 8px;
        margin-bottom: 8px;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s;
        color: #606266;
        font-size: 14px;

        &:hover {
          background: #e6f7ff;
          color: #409eff;
        }

        &.active {
          background: #409eff;
          color: #fff;
        }
      }
    }

    .content {
      flex: 1;
      min-height: 0;
      display: flex;
      flex-direction: column;

      .step-content {
        flex: 1;
        display: flex;
        flex-direction: column;

        .step-header {
          margin-bottom: 16px;
          display: flex;
          gap: 12px;
        }

        .alert-info {
          margin-bottom: 16px;
        }

        .upload-area {
          flex: 1;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;

          .upload-dragger {
            width: 100%;
            max-width: 500px;
          }

          .upload-progress {
            width: 100%;
            max-width: 500px;
            margin-top: 16px;
          }
        }

        .label-config-container {
          display: flex;
          gap: 16px;
          height: 100%;
          min-height: 500px;
          max-height: 700px;
          overflow-y: auto;

          .label-source-panel {
            width: 200px;
            background: #f8f9fa;
            border-radius: 6px;
            padding: 16px;

            .source-title {
              font-weight: 500;
              color: #606266;
              margin-bottom: 16px;
              font-size: 14px;
            }

            .source-items {
              display: flex;
              flex-direction: column;
              gap: 12px;

              .source-item {
                display: flex;
                align-items: center;
                gap: 8px;
                padding: 8px 12px;
                background: #fff;
                border: 1px solid #e4e7ed;
                border-radius: 4px;
                cursor: move;
                transition: all 0.3s;
                color: #606266;

                &:hover {
                  border-color: #409eff;
                  background: #f0f9ff;
                  color: #409eff;
                }

                .el-icon {
                  font-size: 18px;
                }

                span {
                  font-size: 14px;
                }
              }
            }
          }

          .label-config-panel {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #f8f9fa;
            border-radius: 6px;

            .label-header-form {
              margin-bottom: 8px;
              margin-top: 16px;
              border-bottom: 1px solid #e4e7ed;

              .info-icon {
                margin-left: 4px;
                margin-top: 5px;
                color: #909399;
                cursor: help;
                font-size: 18px;
                &:hover {
                  color: #409eff;
                }
              }
            }

            .label-items-wrapper {
              display: flex;
              padding-left: 20px;
              overflow-y: auto;

              .label-items-container {
                width: 100%;
                max-width: 600px;
                display: flex;
                flex-direction: column;
                gap: 0;
                padding: 0;
                background: white;
                border: 1px solid #e0e0e0;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                position: relative;
                overflow: hidden;

                .label-item-card {
                  display: flex;
                  align-items: stretch;
                  gap: 0;
                  padding: 0;
                  background: transparent;
                  border: none;
                  border-radius: 0;
                  box-shadow: none;
                  border-bottom: 1px solid #f0f0f0;
                  height: 60px;

                  &:last-child {
                    border-bottom: none;
                  }

                  .item-left {
                    flex: 1;
                    min-width: 150px;
                    padding: 12px 16px;
                    background-color: #e6f7ff;
                    display: flex;
                    align-items: center;
                    box-sizing: border-box;

                    .item-label {
                      color: #333;
                      font-weight: 500;
                      font-size: 14px;
                    }
                  }

                  .item-right {
                    flex: 1;
                    min-width: 300px;
                    padding: 12px 16px;
                    background: white;
                    border: none;
                    display: flex;
                    align-items: center;
                    box-sizing: border-box;
                    text-align: left;

                    :deep(.el-input) {
                      width: 100%;
                      .el-input__wrapper {
                        background: transparent !important;
                        border: 1px solid #dcdfe6;
                        box-shadow: none !important;
                        padding: 0 12px;
                        border-radius: 4px;
                        height: 36px;
                      }

                      .el-input__inner {
                        color: #303133;
                        font-size: 14px;
                        padding: 0;
                        height: auto;
                        line-height: 36px;
                      }

                      &.is-focus .el-input__wrapper,
                      .el-input__wrapper.is-focus {
                        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) !important;
                        border-color: #409eff !important;
                      }

                      &:hover .el-input__wrapper {
                        border-color: #c0c4cc !important;
                        box-shadow: none !important;
                      }
                    }

                    :deep(.el-select) {
                      width: 100%;
                      .el-input__wrapper {
                        background: transparent !important;
                        border: 1px solid #dcdfe6;
                        box-shadow: none !important;
                        padding: 0 12px;
                        border-radius: 4px;
                        height: 36px;
                      }

                      .el-input__inner {
                        color: #303133;
                        font-size: 14px;
                        padding: 0;
                        height: auto;
                        line-height: 36px;
                      }

                      &.is-focus .el-input__wrapper,
                      .el-input__wrapper.is-focus {
                        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) !important;
                        border-color: #409eff !important;
                      }

                      &:hover .el-input__wrapper {
                        border-color: #c0c4cc !important;
                        box-shadow: none !important;
                      }
                    }

                    .auto-fetch-text {
                      color: #303133;
                      font-size: 14px;
                    }

                    .barcode-preview,
                    .qrcode-preview {
                      height: 40px;
                      display: flex;
                      justify-content: center;
                      overflow: hidden;

                      .barcode-image,
                      .qrcode-image {
                        width: 100%;
                        height: 100%;
                        object-fit: contain;
                      }
                    }
                  }

                  .item-delete {
                    width: 50px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background-color: #fafafa;
                    border-left: 1px solid #f0f0f0;

                    .delete-icon {
                      cursor: pointer;
                      color: #909399;
                      font-size: 18px;
                      transition: all 0.3s;

                      &:hover {
                        color: #f56c6c;
                        transform: scale(1.1);
                      }
                    }
                  }
                }

                .empty-state {
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  height: 200px;
                  padding: 20px;

                  .empty-text {
                    color: #909399;
                    font-size: 14px;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

:deep(.el-upload__text) {
  margin-top: 12px;
  color: #606266;
}

:deep(.el-upload__tip) {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

// 表头样式
.table-header {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;

  .header-drag {
    width: 12px;
    flex-shrink: 0;
    margin-right: 12px;
  }

  // 字段配置表格（7列）
  &.table-header-fields {
    .field-flex-1-7 {
      flex: 1 0 0;
      flex-shrink: 0;
      min-width: 0;
    }
    .field-actions-header {
      width: 120px;
      flex-shrink: 0;
      text-align: center;
    }
  }

  // 加工工序配置表格（3列）
  &.table-header-process {
    .process-flex-1-3 {
      flex: 1 0 0;
      flex-shrink: 0;
      min-width: 0;
    }
    .process-actions-header {
      width: 120px;
      flex-shrink: 0;
      text-align: center;
    }
  }

  // 生产加工单固定字段配置表格（4列）
  &.table-header-production {
    .production-flex-1-4 {
      flex: 1 0 0;
      flex-shrink: 0;
      min-width: 0;
    }
    .production-actions-header {
      width: 120px;
      flex-shrink: 0;
      text-align: center;
    }
  }
}

// 拖拽样式
.ghost {
  opacity: 0.5;
  background: #f0f9ff;
  border: 2px dashed #409eff;
}

.field-item,
.process-item,
.production-item {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  margin-bottom: 8px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: move;
  transition: all 0.3s;

  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
  }

  .drag-handle {
    margin-right: 12px;
    color: #909399;
    cursor: grab;
    display: flex;
    align-items: center;

    &:active {
      cursor: grabbing;
    }
  }

  .field-content,
  .process-content,
  .production-content {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 16px;
    min-width: 0;

    // 字段配置表格列宽（7列）
    .field-flex-1-7 {
      flex: 1 0 0;
      flex-shrink: 0;
      min-width: 0;
    }

    // 加工工序配置表格列宽（3列）
    .process-flex-1-3 {
      flex: 1 0 0;
      flex-shrink: 0;
      min-width: 0;
    }

    // 生产加工单固定字段配置表格列宽（4列）
    .production-flex-1-4 {
      flex: 1 0 0;
      flex-shrink: 0;
      min-width: 0;
    }

    // 统一的单元格文本样式（省略号）
    .cell-text {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      cursor: default;
      width: 100%;
    }

    // 操作列样式（固定宽度120px）
    .field-actions,
    .process-actions,
    .production-actions {
      width: 120px;
      flex-shrink: 0;
      display: flex;
      gap: 8px;
      justify-content: center;
    }
  }
}
</style>
